<template>
  <div>
    <div v-if="method!=='studiedCheck'" class="word-learning-page">
      <!-- 顶部导航栏 -->
      <header v-if="!chooseNext" class="top-nav">
        <div>
          <!-- 回退按钮（靠左） -->
          <el-button
            icon="fa-solid fa-arrow-left"
            class="nav-btn back-btn"
            size="medium"
            @click="$emit('change-view', 'index')"
          />
          <transition
            name="fancy"
            mode="out-in"
            @before-enter="beforeEnter"
            @enter="enter"
          >
            <span
              :key="method"
              class="title-span"
            >{{ showMethodText }}</span>
          </transition>
        </div>
        <div class="top-nav__right">
          <!-- 倍速播放控制（点击展开/收起） -->
          <div ref="speedControlRef" class="speed-control">
            <!-- 速度显示/触发按钮 -->
            <el-button
              class="speed-control__trigger"
              size="medium"
              :icon="showSpeedSlider ? 'fa-solid fa-chevron-up' : 'fa-solid fa-tachometer-alt'"
              @click="toggleSpeedSlider"
            >
              {{ playbackSpeed.toFixed(1) }}x
            </el-button>

            <!-- 展开后的滑块区域 -->
            <div
              v-if="showSpeedSlider"
              class="speed-control__slider-wrap"
            >
              <!-- 滑块 -->
              <el-slider
                v-model="playbackSpeed"
                :min="0.5"
                :max="2"
                :step="0.1"
                :format-tooltip="formatSpeed"
                class="speed-slider"
              />

              <!-- 复位按钮 -->
              <el-button
                class="speed-control__reset-btn"
                size="mini"
                @click="resetSpeed"
              >
                复位 1.0x
              </el-button>
            </div>
          </div>

          <!-- 发音切换 (美式/英式) -->
          <el-button
            class="nav-btn accent-btn"
            size="medium"
            :class="{ 'is-active': true }"
            @click="toggleAccent"
          >
            <span>{{ isAmerican ? '美音' : '英音' }}</span>
          </el-button>

          <!-- 音标显示/隐藏 -->
          <el-button
            class="nav-btn phonetic-btn"
            size="medium"
            @click="togglePhonetic"
          >
            <span :class="['phonetic-label', { 'is-off': !showPhonetic }]">音标</span>
          </el-button>
        </div>
      </header>

      <!-- 页面加载动画 -->
      <div v-if="pageLoading" class="page-loading-container">
        <div class="page-loading-content">
          <i class="el-icon-loading"></i>
          <p>加载单词数据中...</p>
        </div>
      </div>

      <!-- 中间滚动列表区域 -->
      <main v-else class="word-list-container">
        <!--   学新列表   -->
        <div v-if="method === 'new' || method==='review' || method ==='listenToRecognize'" class="word-list">
          <div
            v-for="(word, index) in displayedWords"
            :key="index"
            class="word-item"
            :class="{
              'now-line': word.id === nowClickWord.id && nowClickWord.clickCount>0,
              'next-line': word.studyOrNext === 'next'
            }"
            @click="playPronunciation(word,index)"
          >
            <!-- 单词和音标 -->
            <div class="word-info">
              <div v-if="!(word.clickCount % 3 === 0 && word.clickCount !== 0)" class="word-main">
                <!-- 单词 -->
                <transition name="fade">
                  <h3
                    class="word-text"
                    :class="{'hidden': word.clickCount % 3 === 0 && word.clickCount !== 0}"
                  >
                    <span
                      @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
                    >{{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}</span>
                  </h3>
                </transition>

                <!-- 音标 -->
                <transition name="fade">
                  <p v-if="showPhonetic" class="word-phonetic">
                    <span>{{ isAmerican ? word.phoneticAm : word.phoneticBr }}</span>
                  </p>
                </transition>

                <!-- 单词意思 -->
                <transition name="fade">
                  <div v-if="word.clickCount % 3 === 2" class="word-meaning">
                    <span @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))">{{ word.wordMeaning }}</span>
                  </div>
                </transition>
              </div>
              <div v-else class="word-main">
                <span style="font-size: 24px">🤔</span>
              </div>

              <!-- 添加短语例句按钮 -->
              <el-button
                v-if="word.extendedInfo"
                icon="fa-solid fa-book-open"
                class="phrase-btn"
                size="small"
                @click.stop="showPhraseExample(word)"
              />
            </div>
          </div>
        </div>

        <!--   剪纸盒列表   -->
        <div v-else-if="method==='scissors'" class="word-list">
          <div v-if="!chooseNext">
            <div
              v-for="(word, index) in scissorsList"
              :key="index"
              class="word-item"
              :class="{
                'now-line': word.id === nowClickWord.id && nowClickWord.clickCount>0
              }"
              @click="playPronunciation(word,index)"
            >
              <!-- 单词和音标 -->
              <div class="word-info">
                <div v-if="!(word.clickCount % 3 === 0 && word.clickCount !== 0)" class="word-main2">
                  <div class="word-main">
                    <!-- 单词 -->
                    <transition name="fade">
                      <h3
                        class="word-text"
                        :class="{'hidden': word.clickCount % 3 === 0 && word.clickCount !== 0}"
                      >
                        <span
                          @click.stop="playEn(word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : 'I don\'t know')"
                        >
                          {{ word.fullSpell ? word.fullSpell : word.wordFullSpell ? word.wordFullSpell : '🤔' }}
                        </span>
                      </h3>
                    </transition>

                    <!-- 音标 -->
                    <transition name="fade">
                      <p v-if="showPhonetic" class="word-phonetic">
                        <span @click.stop="playZh(word.wordMeaning.replace(/[A-Za-z]/g, ''))"
                        >{{ isAmerican ? word.phoneticAm : word.phoneticBr }}</span>
                      </p>
                    </transition>

                    <!-- 单词意思 -->
                    <transition name="fade">
                      <div v-if="word.clickCount % 3 === 2" class="word-meaning">
                        <span>{{ word.wordMeaning }}</span>
                      </div>
                    </transition>
                  </div>

                  <!-- 添加短语例句按钮 -->
                  <el-button
                    v-if="word.extendedInfo"
                    icon="fa-solid fa-book-open"
                    class="phrase-btn"
                    size="small"
                    @click.stop="showPhraseExample(word)"
                  />

                  <!-- 快速标记按钮 -->
                  <div class="quick-actions">
                    <el-button
                      icon="fa-solid fa-scissors"
                      class="quick-btn known-btn"
                      @click.stop="toggleKnown(index)"
                    />
                    <el-button
                      v-if="scissorsTimes>1"
                      icon="fa-solid fa-scissors"
                      class="quick-btn unknown-btn"
                      @click.stop="toggleUnknown(index)"
                    />
                  </div>
                </div>
                <div v-else class="word-main">
                  <span style="font-size: 24px">🤔</span>
                </div>
              </div>
            </div>
          </div>

          <div v-else>
            <choose-next
              :have-next-group="groupIndex+1<groupWords.length"
              :show-continue="continueStudy"
              :group-index="groupIndex"
              @handleNextSelect="chooseNextMethod"
            />
          </div>
        </div>
      </main>

      <!-- 底部统计栏 -->
      <footer v-if="!chooseNext">
        <!--  单词学新 底部按钮    -->
        <div v-if="method === 'new' || method==='review' || method ==='listenToRecognize'" class="bottom-nav">
          <div class="foot-left-btn">
            <div>
              <span>第<span class="badge">{{ groupIndex + 1 }}</span>组/共<span class="badge">{{
                  groupWords.length
                }}</span>组</span>
            </div>
          </div>
          <div>
            <el-button
              class="nav-btn start-learn"
              size="medium"
              :disabled="groupIndex + 1 >= groupWords.length"
              @click="nextGroupStudy"
            >
              <i class="fa-solid fa-angles-right"></i>
              下一组
            </el-button>
            <el-button
              class="nav-btn start-learn"
              size="medium"
              @click="disorder"
            >
              <i class="fa-solid fa-teeth-open"></i>
              乱序
            </el-button>
            <el-button
              class="nav-btn start-learn"
              size="medium"
              @click="handleStartLearn"
            >
              <i class="fa-solid fa-scissors"/>
              剪纸盒
            </el-button>
          </div>
        </div>
        <!--  剪纸盒 底部按钮    -->
        <div v-else-if="method==='scissors'" class="bottom-nav bottom-nav2">
          <div></div>
          <div class="word-actions">
            <!-- 能认识 -->
            <div class="can-learn">
              <span>😀</span>
              <span class="badge2">{{ knowScissorsList.length }}</span>
            </div>
            <!-- 不认识 -->
            <div v-if="scissorsTimes>1" class="not-learn">
              <span>😔</span>
              <span class="badge2">{{ unknowScissorsList.length }}</span>
            </div>
          </div>
          <div>
            <el-button
              class="nav-btn start-learn"
              size="medium"
              @click="jumpBoxCheck"
            >
              <i class="fa-solid fa-arrows-turn-right"></i>
              跳过
            </el-button>
            <el-button
              class="nav-btn start-learn"
              size="medium"
              @click="disorderScissors"
            >
              <i class="fa-solid fa-teeth-open"></i>
              乱序
            </el-button>
          </div>
        </div>
      </footer>

      <!--  礼花效果  -->
      <FireworkTransition ref="firework"/>

      <WordDetailDrawer
        :word="currentWordDetail"
        :visible="drawer"
        @update:visible="drawer=false"
      />
    </div>
    <div v-else>
      <!--  学后检测 -->
      <studied-check :check-words="displayedWords" @go-bank="method='scissors'"/>
    </div>
    <!-- 引入单词组对话框组件 -->
    <WordGroupDialog
      v-if="wordGroupShowDialog"
      :visible.sync="wordGroupShowDialog"
      title="自定义分组剪纸盒（仅含已学组）"
      :word-data="groupWords"
      :max-group-index="groupIndex"
      @confirm="handleSelectConfirm"
    />
  </div>
</template>

<script>
import { changeStateAsLean, earlyCompletionOfClasses, groupWord } from '@/api/wordSystemCourse'
import FireworkTransition from '@/views/course/component/courseTeach/wordLearning/FireworkTransition.vue'
import ChooseNext from '@/views/course/component/courseTeach/wordLearning/ChooseNext.vue'
import StudiedCheck from '@/views/course/component/courseTeach/wordLearning/StudiedCheck.vue'
import AudioCacheUtil from '@/utils/AudioCacheUtil'
import WordDetailDrawer from '@/views/course/component/courseTeach/wordLearning/WordDetailDrawer.vue'
import WordGroupDialog from '@/views/course/component/courseTeach/wordLearning/WordGroupDialog.vue'

export default {
  name: 'LearnPage',
  components: { WordGroupDialog, WordDetailDrawer, StudiedCheck, ChooseNext, FireworkTransition },
  props: {
    bundleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      wordGroupShowDialog: false, // 单词组对话框显示状态
      isAmerican: true, // 美式发音
      showPhonetic: true, // 显示音标
      playbackSpeed: 1.0, // 播放速度
      isLoading: false, // 是否加载中
      pageLoading: true, // 页面加载状态
      hasMoreData: true, // 是否有更多数据
      // 新增：控制倍速滑块展开/收起
      showSpeedSlider: false,

      // 单词数据
      groupWords: [], // 所有单词
      groupIndex: 0,
      nextIndex: 0,
      nextSequence: [],
      displayedWords: [], // 显示的单词
      // new 学新 review 复习 // scissors 剪纸盒
      method: 'new',
      nowClickWord: {},
      continueStudy: false,

      scissorsList: [], // 剪纸盒数组
      knowScissorsList: [], // 剪纸盒数组 掌握
      unknowScissorsList: [], // 剪纸盒数组 未掌握
      scissorsTimes: 1,
      chooseNext: false, // 剪纸盒完毕后选择页面

      drawer: false, // 抽屉
      currentWordDetail: {}
    }
  },
  computed: {
    showMethodText() {
      return this.method === 'new' ? '生词识记'
        : this.method === 'review' ? '单词复习'
          : this.method === 'listenToRecognize' ? '听音识词'
            : this.method === 'scissors' ? '剪纸盒' : '学后检测'
    }
  },
  watch: {
    // 判断当前点击的按钮是否为连续点击 如果不是 需要将上一次的按钮点击次数清零
    'nowClickWord'(newValue, oldValue) {
      if (newValue.id !== oldValue.id) {
        oldValue.clickCount = 0
      }
    },

    'method'() {
      this.nowClickWord = this.displayedWords[0]
      this.nowClickWord.clickCount = 0
    }
  },
  // ✅ 新增：组件销毁时清除监听
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
  },
  created() {
    // 初始化加载第一页数据
    this.loadWords()
  },
  methods: {
    chooseNextMethod(name) {
      this.nowClickWord = {}
      if (name === '重新剪纸盒') {
        this.chooseNext = false
        // 下面是数据初始化
        this.method = 'scissors'
        this.scissorsTimes = 1
        this.scissorsList = []
        this.displayedWords = this.groupWords[this.groupIndex]
        this.displayedWords.forEach(word => {
          this.scissorsList.push(word)
        })
        this.nowClickWord = {}
        this.scissorsTimes = 1
      } else if (name === '学习下一组') {
        this.chooseNext = false
        this.method = 'new'
        this.nextIndex = 0
        this.loadWords(false)
        this.method = 'new'
      } else if (name === '全部混组') {
        this.chooseNext = false
        // 下面是数据初始化
        this.method = 'scissors'
        this.scissorsList = []
        this.displayedWords = []
        this.groupWords.forEach(list => {
          list.forEach(word => {
            this.displayedWords.push(word)
          })
        })
        this.displayedWords.forEach(word => {
          this.scissorsList.push(word)
        })
        this.nowClickWord = {}
        this.scissorsTimes = 1
      } else if (name === '自定义混组') {
        this.wordGroupShowDialog = true
      } else if (name === '学后检测') {
        this.method = 'studiedCheck'
        this.displayedWords = []
        this.groupWords.forEach(list => {
          list.forEach(word => {
            this.displayedWords.push(word)
          })
        })
        this.continueStudy = true
      } else if (name === '继续学新') {
        this.$emit('continue-study')
      } else if (name === '提前结课') {
        this.$msgbox({
          title: '友情提示',
          message: '是否提前结课？',
          showCancelButton: true,
          confirmButtonText: '提前结课',
          cancelButtonText: '我点错了',
          type: 'warning'
        }).then(async() => {
          try {
            await earlyCompletionOfClasses()
          } finally {
            this.$router.push({ path: `/afterClass?cid=${this.$route.query.q1}` })
          }
        }).catch(() => {
        })
      }
    },
    handleSelectConfirm(data) {
      console.log(data)
      this.chooseNext = false
      // 下面是数据初始化
      this.method = 'scissors'
      this.scissorsList = []
      this.displayedWords = []
      data.groups.forEach(item => {
        item.wordList.forEach(word => {
          this.displayedWords.push(word)
        })
      })
      this.displayedWords.forEach(word => {
        this.scissorsList.push(word)
      })
      this.nowClickWord = {}
      this.scissorsTimes = 1
    },
    // 点击学习下一组
    nextGroupStudy() {
      if (this.groupIndex + 1 >= this.groupWords.length) {
        return
      }
      this.$msgbox({
        title: '友情提示',
        message: '进入下一组学习，并且将本组单词标记为已学状态，是否继续？',
        showCancelButton: true,
        confirmButtonText: '继续',
        cancelButtonText: '我点错了',
        type: 'warning'
      }).then(async(action) => {
        const idArr = this.displayedWords.map(word => word.id)
        this.chooseNextMethod('学习下一组')
        await changeStateAsLean(idArr)
      }).catch(() => {
      })
    },
    // 剪纸盒
    async handleStartLearn() {
      if (this.method !== 'listenToRecognize' && !sessionStorage.getItem('listenToRecognizeNoCompeteTime')) {
        // 听音识词未完成次数
        sessionStorage.setItem('listenToRecognizeNoCompeteTime', 1)
        await this.$msgbox({
          title: '友情提示',
          message: '当前尚未完成学习，是否直接进入剪纸盒？',
          showCancelButton: true,
          confirmButtonText: '我已知晓',
          cancelButtonText: '我点错了',
          type: 'warning'
        }).then((action) => {
          this.method = 'scissors'
        }).catch(() => {
        })
        if (this.method !== 'scissors') {
          return
        }
      }
      this.method = 'scissors'
      this.scissorsList = []
      this.scissorsTimes = 1
      this.displayedWords.forEach(word => {
        this.scissorsList.push(word)
      })
      this.nowClickWord = {}
    },
    // 乱序 对单词顺序进行打乱
    disorder() {
      const arr = [...this.displayedWords]
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[arr[i], arr[j]] = [arr[j], arr[i]]
      }
      this.displayedWords = arr

      this.displayedWords.forEach(word => {
        this.$set(word, 'clickCount', 0)
        this.$set(word, 'studyOrNext', '')
      })
      this.nowClickWord = this.displayedWords[0]
      this.nextIndex = 0
      if (this.method !== 'listenToRecognize') {
        this.displayedWords[this.nextSequence[this.nextIndex]].studyOrNext = 'next'
      }
    },
    disorderScissors() {
      const arr = [...this.scissorsList]
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[arr[i], arr[j]] = [arr[j], arr[i]]
      }
      this.scissorsList = arr
    },
    // 格式化速度显示
    formatSpeed(value) {
      return `${value}x`
    },

    // 切换发音（美式/英式）
    toggleAccent() {
      this.isAmerican = !this.isAmerican
    },

    // 切换音标显示/隐藏
    togglePhonetic() {
      this.showPhonetic = !this.showPhonetic
    },

    toggleUnknown(index) {
      this.unknowScissorsList.push(this.scissorsList[index])
      this.scissorsList.splice(index, 1)
      if (this.scissorsList.length === 0 && this.unknowScissorsList.length > 0) {
        this.scissorsList = this.unknowScissorsList
        this.unknowScissorsList = []
      }
    },

    /**
     * 剪纸盒步过
     * @returns {Promise<void>}
     */
    async jumpBoxCheck() {
      this.$refs.firework.setDuration(1000).startConfetti('🥳🥳🥳')
      // 更改本组单词学习状态为已学
      const idArr = this.scissorsList.map(word => word.id)
      this.chooseNext = true
      await changeStateAsLean(idArr)
    },

    async toggleKnown(index) {
      this.knowScissorsList.push(this.scissorsList[index])
      this.scissorsList.splice(index, 1)
      if (this.scissorsList.length === 0 && this.unknowScissorsList.length === 0) {
        this.scissorsList = this.knowScissorsList
        this.knowScissorsList = []
        this.scissorsTimes++
      } else if (this.scissorsList.length === 0 && this.unknowScissorsList.length > 0) {
        this.scissorsList = this.unknowScissorsList
        this.unknowScissorsList = []
      }
      if (this.scissorsTimes > 2) {
        this.$refs.firework.setDuration(1000).startConfetti('🥳🥳🥳')
        // 更改本组单词学习状态为已学
        const idArr = this.scissorsList.map(word => word.id)
        this.chooseNext = true
        await changeStateAsLean(idArr)
      }
    },

    playZh(text) {
      AudioCacheUtil.play(text, 'zh', this.playbackSpeed)
    },

    playEn(text) {
      AudioCacheUtil.play(text, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },

    // 播放单词发音
    playPronunciation(word, index) {
      if (this.method !== 'listenToRecognize') {
        if (this.nextIndex < this.nextSequence.length && index === this.nextSequence[this.nextIndex]) {
          // 点击的是下一个指定的 那么更新下下一个指定的单词
          this.nextIndex++
          if (this.nextIndex < this.nextSequence.length) {
            this.displayedWords[this.nextSequence[this.nextIndex]].studyOrNext = 'next'
            this.displayedWords[this.nextSequence[this.nextIndex - 1]].studyOrNext = ''
          }
        }
        // 当光标消失后并且跳出了当前单词（或者是只有一个单词的时候点击次数大于5次） 则代表要进入复习 或者是听音识词
        if (this.nextIndex >= this.nextSequence.length &&
          (word.id !== this.nowClickWord.id ||
            (this.displayedWords.length === 1 &&
              word.clickCount > 5))) {
          // 最后一个单词单词不处于隐藏 那么代表要进入复习 或者是听音识词
          this.nextIndex = 0
          word.studyOrNext = ''
          word.clickCount = 0
          if (this.method === 'new') {
            // 进入复习
            this.method = 'review'
            // 重新获取序列
            this.nextSequence = this.generateSequenceReview(this.displayedWords.length)
            this.displayedWords[this.nextSequence[this.nextIndex]].studyOrNext = 'next'
            // 礼花效果
            // this.$refs.firework.startConfetti('完成学习 开始复习')
          } else if (this.method === 'review') {
            // 进入听音识词
            this.displayedWords[this.nextSequence[this.nextIndex]].studyOrNext = ''
            this.method = 'listenToRecognize'
            // this.$refs.firework.startConfetti('完成复习 听音识词')
          }
        }
      }

      word.clickCount++
      this.nowClickWord = word

      AudioCacheUtil.play(word.fullSpell ? word.fullSpell : word.wordFullSpell, this.isAmerican ? 'en' : 'uk', this.playbackSpeed)
    },

    // 加载单词数据
    async loadWords(server = true) {
      this.isLoading = true
      this.pageLoading = true
      try {
        if (server) {
          this.groupWords = await groupWord({ bundleId: this.bundleId })
        } else {
          this.groupIndex++
        }
        this.displayedWords = this.groupWords[this.groupIndex]
        this.nextSequence = this.generateSequence(this.displayedWords.length)
        this.displayedWords[this.nextSequence[this.nextIndex]].studyOrNext = 'next'
        this.displayedWords.forEach(word => {
          this.$set(word, 'clickCount', 0)
        })
        this.nowClickWord = this.displayedWords[0]
      } catch (error) {
        console.error('加载单词数据失败:', error)
        this.$notify({ type: 'error', message: '加载单词数据失败，请重试' })
      } finally {
        this.pageLoading = false
        this.isLoading = false
      }
    },
    /**
     * 生成数字序列（下一个的顺序）
     * @param n
     * @returns {number[]|*[]}
     */
    generateSequence(n = 1) {
      if (n <= 0) return []
      if (n === 5) {
        const arr = [1, 2, 1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 4, 5, 2, 1, 2]
        arr.forEach((item, index) => {
          arr[index] = item - 1
        })
        return arr
      }
      const result = [1 - 1] // 初始 n=1 的情况
      for (let i = 2; i <= n; i++) {
        // 1. 先接上新数字 i
        result.push(i - 1)
        // 2. 然后补一个“下降再上升”的序列 (i-1 ... 1 ... i)
        for (let j = i - 1; j >= 1; j--) {
          result.push(j - 1)
        }
        for (let j = 2; j <= i; j++) {
          result.push(j - 1)
        }
      }

      return result
    },

    generateSequenceReview(n = 1) {
      if (n <= 1) {
        return [1 - 1]
      }
      const result = []
      for (let i = 1; i <= n; i++) {
        result.push(i - 1)
      }
      for (let i = n - 1; i >= 1; i--) {
        result.push(i - 1)
      }
      return result
    },
    // ✅ 修改 toggleSpeedSlider 方法
    toggleSpeedSlider() {
      this.showSpeedSlider = !this.showSpeedSlider

      // ✅ 如果展开，则绑定 document 点击监听；否则解绑
      if (this.showSpeedSlider) {
        document.addEventListener('click', this.handleClickOutside)
      } else {
        document.removeEventListener('click', this.handleClickOutside)
      }
    },
    // ✅ 新增：点击外部关闭滑块
    handleClickOutside(e) {
      const controlEl = this.$refs.speedControlRef
      if (controlEl && !controlEl.contains(e.target)) {
        this.showSpeedSlider = false
        document.removeEventListener('click', this.handleClickOutside)
      }
    },

    // 新增：复位播放速度到1.0x
    resetSpeed() {
      this.playbackSpeed = 1.0
      // 复位后可选择自动收起滑块
      this.showSpeedSlider = false
      document.removeEventListener('click', this.handleClickOutside) // ✅ 防止监听残留
    },

    beforeEnter(el) {
      // 初始状态
      el.style.transform = 'scale(1)'
      el.style.color = '#000'
      el.style.opacity = 1
    },
    enter(el, done) {
      // 动画序列
      const animation = el.animate([
        { transform: 'scale(1)', color: '#000', opacity: 1 }, // 初始
        { transform: 'scale(1.5)', color: '#ff4d4f', opacity: 0.8 }, // 膨胀 + 变色 + 半透明
        { transform: 'scale(1.2)', color: '#ffec3d', opacity: 1 }, // 回弹 + 闪黄
        { transform: 'scale(1)', color: '#000', opacity: 1 } // 恢复
      ], {
        duration: 700,
        easing: 'ease-in-out'
      })

      animation.onfinish = done
    },
    showPhraseExample(word) {
      this.drawer = true
      this.currentWordDetail = word
    }
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.word-learning-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f5f7fa;
}

/* 中间单词列表区域 */
.word-list-container {
  height: 100%;
  flex-grow: 1;
  overflow: hidden;
  padding: 5px;
}

.word-list {
  height: 100%;
  overflow-y: auto;
}

.word-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  min-height: 40px;
  user-select: none;
}

.word-main {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.word-main2 {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.word-text {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

  position: relative;
  user-select: none;

  span {
    cursor: pointer;
  }
}

.word-text.hidden {
  color: transparent;
  text-shadow: 0 0 12px #999;
  filter: blur(6px);
  transition: filter 0.3s ease, text-shadow 0.3s ease;
}

.word-phonetic {
  font-size: 18px;
  color: #999;
  margin: 10px 0 0 0;
  font-style: italic;
}

.word-meaning {
  color: #555;
  margin-top: 20px;

  span {
    cursor: pointer;
  }
}

.title-span {
  display: inline-block; /* 必须行内块元素才能做 transform */
  font-weight: bold;
}

/* 加载状态 */
.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px;
  color: #666;
}

.no-more {
  text-align: center;
  padding: 24px;
  color: #999;
}

/* 底部菜单栏 */
.bottom-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 56px;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 滚动条美化 */
.word-list::-webkit-scrollbar {
  width: 0;
}

/* 顶部导航栏整体样式 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 左右布局分离 */
  padding: 0 16px;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative; /* 为滑块下拉层提供定位基准 */
}

/* 右侧功能区容器（统一靠右） */
.top-nav__right {
  display: flex;
  align-items: center;
  gap: 12px; /* 按钮间距统一 */
}

/* 统一按钮基础样式 */
.nav-btn {
  padding: 8px 12px;
  border-radius: 20px; /* 圆角更柔和 */
  background-color: transparent;
  color: #333;
  transition: all 0.2s ease;
  border: 1px solid transparent;
  font-size: 14px;
}

.nav-btn:hover {
  background-color: #f5f7fa;
  border-color: #e0e0e0;
}

.start-learn {
  border: 1px solid #e0e0e0;
}

.start-learn:hover {
  color: #0084ff;
}

/* 发音按钮激活态（增强视觉反馈） */
.accent-btn.is-active {
  background-color: #e6f4ea;
  color: #239744;
  border-color: #d1e7dd;
}

/* 倍速控制容器 */
.speed-control {
  position: relative; /* 滑块下拉层相对定位 */
  display: flex;
  align-items: center;
}

/* 倍速触发按钮 */
.speed-control__trigger {
  padding: 8px 12px;
  border-radius: 20px;
  background-color: #f5f7fa;
  color: #333;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px; /* 图标与文字间距 */
}

.speed-control__trigger:hover {
  background-color: #e9ecef;
  border-color: #dee2e6;
}

/* 倍速滑块容器（下拉层） */
.speed-control__slider-wrap {
  position: absolute;
  top: 60px; /* 位于触发按钮下方 */
  left: -50px;
  width: 220px;
  padding: 12px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 20; /* 确保在其他元素上方 */
  /* 淡入动画 */
  animation: fadeIn 0.2s ease forwards;
}

/* 滑块样式 */
.speed-slider {
  flex-grow: 1;
  margin: 0;
}

/* 复位按钮样式 */
.speed-control__reset-btn {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f0f9ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.speed-control__reset-btn:hover {
  background-color: #e6f7ff;
  border-color: #69c0ff;
}

/* 音标按钮样式（保持原有逻辑，优化细节） */
.phonetic-label {
  position: relative;
  display: inline-block;
  padding: 0 2px;
  color: #333;
  transition: color 0.2s ease;
}

.phonetic-label::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: 2px;
  top: 50%;
  transform: translateY(-50%) scaleX(0);
  transform-origin: left center;
  background: #ff4d4f; /* 横线用醒目红色 */
  transition: transform 0.25s cubic-bezier(.2, .9, .2, 1);
  pointer-events: none;
}

.phonetic-label.is-off {
  color: #999;
}

.phonetic-label.is-off::after {
  transform: translateY(-50%) scaleX(1);
}

/* 淡入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.phonetic-btn {
  margin: 0;
}

/* 默认卡片样式 */
.word-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 10px;
  margin-top: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border-left: 6px solid transparent;
  cursor: pointer;
}

.word-item:hover {
  transform: translateY(-2px);
}

/* 认识状态：淡绿色背景 */
.word-item.now-line {
  background-color: #e6f7ed;
  border: 1px solid #239744;
}

/* 不认识状态：淡红色背景 */
.word-item.next-line {
  border-left-color: #3498db;
}

/* 按钮默认透明，选中时保留高亮 */
.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent;
  border: 1px solid #ccc;
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #239744 !important;
  color: #fff !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #e53e3e !important;
  color: #fff !important;
  border-color: #e53e3e !important;
}

/* 徽标样式 */
.badge {
  padding: 0 6px;
  border-radius: 10px;
  background-color: #0084ff;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

.quick-actions {
  display: flex;
  gap: 5px;
  margin-left: auto;
}

.quick-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0;
  border-radius: 50%;
  background-color: transparent; /* 默认透明 */
  border: 1px solid #ccc; /* 给个轻微边框 */
  color: #555;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background-color: #f5f5f5;
}

.known-btn {
  background-color: #e6f7ed !important;
  color: #239744 !important;
  border-color: #239744 !important;
}

.unknown-btn {
  background-color: #fde2e2 !important;
  color: #e53e3e !important;
  border-color: #e53e3e !important;
}

.bottom-nav2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.word-actions {
  display: flex;
  gap: 40px;
  margin-top: 12px;
  position: relative;

  div {
    font-size: 40px;
  }

  .not-learn {
    color: rgb(229, 62, 62);
  }

  .can-learn {
    color: rgb(35, 151, 68);
  }
}

.word-actions > div {
  position: relative;
  font-size: 40px;
}

/* 徽标样式 */
.badge2 {
  position: absolute;
  top: -6px;
  right: -10px;
  min-width: 20px;
  height: 20px;
  padding: 0 6px;
  border-radius: 10px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

/* 认识用绿色徽标 */
.can-learn .badge2 {
  background-color: #52c41a;
}

/* 不认识用红色徽标 */
.not-learn .badge2 {
  background-color: #ff4d4f;
}

.word-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #00b578;
}

.word-item:hover span,
.word-item:hover h3 {
  color: white;
}

/* 短语例句按钮样式 */
.phrase-btn {
  width: 36px;
  height: 36px;
  padding: 0;
  margin: 0 8px;
  border-radius: 50%;
  background-color: #f0f7ff !important;
  color: #1890ff !important;
  border-color: #91d5ff !important;
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.phrase-btn:hover {
  background-color: #e6f7ff !important;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.phrase-btn:active {
  transform: scale(0.95);
}

/* 调整剪纸盒模式下的按钮布局 */
.word-main2 {
  align-items: center; /* 确保按钮垂直居中 */
}

.page-loading-content {
  text-align: center;
  color: #909399;
}

.page-loading-content i {
  font-size: 40px;
  margin-bottom: 16px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.page-loading-content p {
  font-size: 16px;
}

/* 添加旋转动画 */
@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 修改底部导航栏高度，确保加载容器计算正确 */
.bottom-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 56px; /* 明确高度 */
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 确保顶部导航栏高度固定 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 50px; /* 明确高度 */
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  position: relative;
}

/* 为加载中的按钮添加样式 */
.start-learn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 页面加载动画样式 */
.page-loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.page-loading-content {
  text-align: center;
  color: #909399;
}

.page-loading-content i {
  font-size: 40px;
  margin-bottom: 16px;
  color: #409EFF;
  animation: rotating 2s linear infinite;
}

.page-loading-content p {
  font-size: 16px;
}

.foot-left-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}
</style>
